# -*- coding: utf-8 -*-
# vim: set noet ts=4:
#
# scim-python
#
# Copyright (c) 2007-2008 Yu Fan <yufanyufan@gmail.com>
#
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA  02111-1307  USA
#
# $Id: $
#
import scim
import os
import traceback
import sys
from gettext import dgettext


from ibus import keysyms
from ibus import modifier
from ibus import ascii

from npengine import *
from PYDict import *

_ = lambda a : dgettext ("ibus-natural-pinyin", a)

class ShuangPinEngine (Engine):

	
	def __init__ (self, conn, object_path):
		Engine.__init__(self, conn, object_path)
		
	def clear(self):
		self.extra_string = []
		Engine.clear(self)

	def get_extra_string(self):
		return "".join(self.extra_string)

	@classmethod
	def CONFIG_RELOADED(cls, config):
		ShuangPinEngine.schema = config.get_value("engine/NaturalPinYin", "ShuangPinSchema", "MSPY")
		#~ print self.schema
		if not ShuangPinEngine.schema in SHUANGPIN_SCHEMAS.keys ():
			ShuangPinEngine.schima = "MSPY"
		(ShuangPinEngine.shengmu_schema, ShuangPinEngine.yunmu_schema) = SHUANGPIN_SCHEMAS[ShuangPinEngine.schema]
		
	def translate(self, keyval):
		if(self._editor.current () == None or self._editor.current ().is_complete ()):
			if unichr (keyval) in self.shengmu_schema:
				self._editor.pinyinlist.append (PinYinWord(self.shengmu_schema[unichr (keyval)],""))
				if not self.progresivepromp:
					return
			else:
				raise InputException()
		else:
			if unichr(keyval) in self.yunmu_schema:
				yunmu = self.yunmu_schema[unichr(keyval)]
				p = None
				for i in yunmu:
					pinyin = self._editor.current ().get_shengmu () + i
					if pinyin in PINYIN_LIST:
						p = i
						break
				if p == None:
					raise InputException ()
				self._editor.current().set_yunmu (p)
			else:
				raise InputException
		self._editor.auto_convert ()
		


	def chinese_process_key_event (self, keyval, keycode, state):
		if (ShuangPinEngine.schema=="MSPY" or ShuangPinEngine.schema=="ZGPY") and \
			(state & (ibus.modifier.CONTROL_MASK | ibus.modifier.ALT_MASK | ibus.modifier.SHIFT_MASK )) == 0 and (\
			(keyval >= ibus.keysyms.a and keyval <= ibus.keysyms.z) or \
			keyval == ibus.keysyms.semicolon):
			self.translate(keyval)
			return True
		elif (state & (ibus.modifier.CONTROL_MASK | ibus.modifier.ALT_MASK | ibus.modifier.SHIFT_MASK )) == 0 \
			and (keyval >= ibus.keysyms.a and keyval <= ibus.keysyms.z):
			self.translate(key)
			return True
		elif self._editor.pinyinlist and keyval == ibus.keysyms.BackSpace:
			if self._editor.pinyinlist[-1].is_complete ():
				self._editor.pinyinlist[-1].set_yunmu ("")
				if not self.progresivepromp:
					return True
			else:
				del self._editor.pinyinlist[-1]
			self._editor.update ()
			return True
		elif (self.extra_string or self._editor.pinyinlist) and (keyval == ibus.keysyms.Left or keyval == ibus.keysyms.f and key.mask & ibus.modifier.CONTROL_MASK):
			if self._editor.pinyinlist:
				p = self._editor.pinyinlist[-1].get_screen_pinyin()
				self.extra_string = [p] + self.extra_string
				del self._editor.pinyinlist[-1]
				self._editor.update ()
			return True
		elif (self._editor.pinyinlist or self.extra_string ) and (keyval == ibus.keysyms.Right or keyval == ibus.keysyms.b and key.mask & ibus.modifier.CONTROL_MASK):
			if self.extra_string:
				self._editor.pinyinlist.append(PinYinWord(pinyin=self.extra_string[0]))
				del self.extra_string[0]
				self._editor.update ()
				return True
			else:
				raise InputException()
		elif (self._editor.pinyinlist or self.extra_string ) and keyval == ibus.keysyms.Delete:
			if self.extra_string:
				del self.extra_string[0]
				return True
			else:
				raise InputException()
		elif self.extra_string and keyval in (ibus.keysyms.KP_Space, ibus.keysyms.space):
			while self.extra_string:
				self._editor.pinyinlist.append(PinYinWord(pinyin=self.extra_string[0]))
				del self.extra_string[0]
			self._editor.auto_convert ()
			return True
		elif Engine.chinese_process_key_event (self,keyval, keycode, state):
			return True;
		return False

def test_add_char(editor, char):
	if(editor.current () == None or editor.current ().is_complete ()):
		editor.pinyinlist.append(PinYinWord(MSPY_SHUANGPIN_SHENGMU_DICT[char],""))
	else:
		yunmu = MSPY_SHUANGPIN_YUNMU_DICT[char]
		p = None
		for i in yunmu:
			pinyin = editor.current ().get_shengmu() + i
			if pinyin in PINYIN_LIST:
				p = i
				break
		if p == None:
			raise Exception ()
		editor.current ().set_yunmu (p)
	editor.auto_convert ()

def test_case(pinyin,modify = None, sentence=None):
	editor = Editor ()
	editor.schema = "MSPY"
	editor.userword = True
	editor.userphrase = True
	editor.adjustfreq = True
	
	(editor.shengmu_schema, editor.yunmu_schema) = SHUANGPIN_SCHEMAS [editor.schema]
	for i in pinyin:
		test_add_char (editor,i)
	editor.convert_all ()
	if modify:
		for i in range (0,len(modify)):
			editor.wordlist[i].char=modify[i]
	result = editor.commit ()
	print result
	if sentence:
		assert editor.commit () == sentence

def test():
	test_case("fhdiijklfauhdedstmjqykllle")
	test_case("woxihr")
	test_case("hvbuhvybufme")
	test_case("zfmehvuioa")
	test_case("kklydkde")
	test_case("devild")
	test_case("veybvuyu")

if __name__ == "__main__":
	#~ import timeit
	#~ t = timeit.Timer("ShuangPin.test()","import ShuangPin")
	#~ print t.repeat(1,1)
	import cProfile
	cProfile.run("test()","fooprof")
	import pstats
	p = pstats.Stats("fooprof")
	p.strip_dirs().sort_stats("cumulative").print_stats()
